'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useAuth } from '@/contexts/auth-context'
import { ToolFormWrapper } from '@/components/tools/tool-form-wrapper'
import { LoadingState } from '@/components/ui/loading-spinner'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'

export default function EditToolPage() {
  const { id } = useParams()
  const { user, loading: authLoading } = useAuth()
  const router = useRouter()
  const [tool, setTool] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/login?redirect=/profile')
      return
    }

    if (user && id) {
      fetchTool()
    }
  }, [user, authLoading, id])

  const fetchTool = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/tools/${id}`)
      const result = await response.json()

      if (response.ok) {
        // 检查是否是工具的所有者
        if (result.data.userId !== user?.id) {
          setError('您没有权限编辑此工具')
          return
        }
        setTool(result.data)
      } else {
        setError(result.error || '工具不存在')
      }
    } catch (error) {
      setError('加载工具信息失败')
    } finally {
      setLoading(false)
    }
  }

  if (authLoading || loading) {
    return <LoadingState message="加载工具信息中..." />
  }

  if (!user) {
    return <LoadingState message="跳转到登录页面..." />
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <Card>
            <CardHeader>
              <CardTitle className="text-red-600">错误</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-gray-600 mb-4">{error}</p>
              <button
                onClick={() => router.back()}
                className="text-blue-600 hover:text-blue-700"
              >
                返回上一页
              </button>
            </CardContent>
          </Card>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900">编辑工具</h1>
          <p className="mt-2 text-gray-600">
            更新您的工具信息
          </p>
        </div>
        
        {tool && <ToolFormWrapper initialData={tool} isEdit={true} />}
      </div>
    </div>
  )
}
